package co.za.itweb.itwebafrica;



import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.text.method.LinkMovementMethod;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint({ "SetJavaScriptEnabled", "WorldReadableFiles" })
public class SingleLatest extends FragmentActivity {
	public int TWITTER_AUTH;
	public Twitter mTwitter;
	public RequestToken mRequestToken;

	public String accessToken;
	public String accessTokenSecret;

	public boolean haveConnectedWifi;
	public boolean haveConnectedMobile;
	public double x;
	static ImageButton tweetB;
	protected static final String PREFS_NAME = "FAVORITES";

	private Integer newsValue;
	
	String title;

	int fontsize;
	public static int screenWidth;
	public static int screenHeight;
	public static ImageLoader imageLoader;

	Dialog dialog;
	Dialog emaildialog;

	ArrayAdapter<String> favorites;
	Integer feedValue;
	
	static ProgressDialog pdialog;

	
	TextView text;
	Banner myFragmentBanner;
	Disquss myFragmentDisquss;
	 TweetTask tt;
	 ResumeTask rt;
	 UpdateTask ut;
	String oauthVerifier;
	int id;

	private int width;
	private WebView myWebView;
	private String density2;
	private int bannerHolderWidth2;
	public void onCreate(Bundle icecream) {
		super.onCreate(icecream);
		setContentView(R.layout.onenews);
		
		
		
		Bundle extras = getIntent().getExtras();
		 feedValue = extras.getInt("feedid");

		newsValue = extras.getInt("id");
		if(feedValue==null || newsValue==null){
			SingleLatest.this.finish();
		}
		// View vi = inflater.inflate(R.layout.onenews, null);

			title = "Latest News";
	 

		LinearLayout layout = (LinearLayout) findViewById(R.id.cell3);
		 int colors[] =  {Color.parseColor("#ee3126"),Color.parseColor("#9c1e17")};
		GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,
				colors);
		layout.setBackgroundDrawable(grad);

		 Bundle args = new Bundle();
		  args.putString("articleID",FirstScreen.fList.get(feedValue)._itemlist
					.get(newsValue).getId().toString());
		  args.putString("articleTITLE",FirstScreen.fList.get(feedValue)._itemlist
					.get(newsValue).getTitle().toString());
		 
		  Bundle args2 = new Bundle();
		  args2.putString("catID",FirstScreen.fList.get(feedValue)._itemlist
					.get(newsValue).getCategory().toString());
		myFragmentBanner = new Banner();
		myFragmentBanner.setArguments(args2);
		getSupportFragmentManager().beginTransaction()
				.add(R.id.fragmentbanner, myFragmentBanner).commit();

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);

	
		
		 width = metrics.widthPixels;
		 if(FirstScreen.fList.get(feedValue)._itemlist.get(newsValue).getId().length()>6){
				
				RelativeLayout linLayout = (RelativeLayout) findViewById(R.id.youtube);
				RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
				

				 myWebView = new WebView(SingleLatest.this); 
				linLayout.addView(myWebView, layoutParams);
				
				

				 ((WebView) myWebView).getSettings().setJavaScriptEnabled(true);


		        ((WebView) myWebView).loadUrl("http://www.youtube.com/watch?v="+FirstScreen.fList.get(feedValue)._itemlist.get(newsValue).getId().toString()); 
		        
		        
				
				}else{
					
					RelativeLayout linLayout = (RelativeLayout) findViewById(R.id.disquss);
				
					if(determineDensity()=="ldpi"){
						bannerHolderWidth2=(int) (int) (width+(width/3))-10;
					}else if(determineDensity()=="mdpi"){
						bannerHolderWidth2=(int) (width)-10;
					}else if(determineDensity()=="hdpi"){
						
						bannerHolderWidth2=(int)  (width-(width/3))-10;
						
					}else if(determineDensity()=="xdpi"){
						bannerHolderWidth2=(int)width+(width/2)-10;
					}
					RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(width,LayoutParams.WRAP_CONTENT);
					

					 myWebView = new WebView(SingleLatest.this); 
					linLayout.addView(myWebView, layoutParams);
					
				String articleID =FirstScreen.fList.get(feedValue)._itemlist.get(newsValue).getId().toString();
				String articleTITLE =FirstScreen.fList.get(feedValue)._itemlist.get(newsValue).getTitle().toString();
				String articleURL =FirstScreen.fList.get(feedValue)._itemlist.get(newsValue).getLink().toString();
					((WebView) myWebView).getSettings().setJavaScriptEnabled(true);

					int currentapiVersion = android.os.Build.VERSION.SDK_INT;
					if (currentapiVersion <= android.os.Build.VERSION_CODES.GINGERBREAD){

					((WebView) myWebView).setWebViewClient(new WebViewClient() {

					}); 
					
					((WebView) myWebView).loadData("<html><head><meta name=\"viewport\" content=\"minimum-scale=1.0; maximum-scale=1.0; user-scalable=false; initial-scale=1.0;\"/><style>html,body,iframe{margin:0;padding:0;}</style></head><body><iframe style=\"width:"+bannerHolderWidth2+"px;height:600px;border:0px;margin:0px;\" src=\"http://itweb.mobi/disqus-itwebafrica.php?id="+articleID+"&url="+articleURL+"&source=android&tag=article&title="+articleTITLE+"\"></iframe></body></html>", "text/html", null);
					
					}else{
					
						((WebView) myWebView).setWebViewClient(new WebViewClient() {
						
							
						}); 
						((WebView) myWebView).setWebChromeClient(new WebChromeClient() {
							@Override
							public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result) {
								Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
								  result.confirm();
								  return true;
						       }
					 });
					
						((WebView) myWebView).loadData("<div></div>", "text/html","utf8");//added for dom so that we can have something on page before loading disqus
						 ((WebView) myWebView).loadUrl("http://itweb.mobi/disqus-itwebafrica.php?id="+articleID+"&url="+articleURL+"&source=android&tag=article&title="+articleTITLE);
					}

				}
		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(SingleLatest.this);
		accessToken = settings.getString("twitter_access_token", null);
		accessTokenSecret = settings.getString("twitter_access_token_secret",
				null);
		tt = new TweetTask(this);
		rt = new ResumeTask();
		ut = new UpdateTask(this);
		
		tweetB = (ImageButton) findViewById(R.id.tweet_button);

		tweetB.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				tweetB.setBackgroundResource(R.drawable.twitter_visited);
				tweetB.setClickable(false);
				if (accessToken == null || accessToken.length() < 2) {
					tt.execute();
				} else {
					
					ut.execute();

				}

			}
		});

		TextView titletext = (TextView) findViewById(R.id.title);
		titletext.setText(title + " article");

		ImageButton back = (ImageButton) layout.findViewById(R.id.back);
//		ImageButton find = (ImageButton) layout.findViewById(R.id.find);

		// ImageButton refresh=(ImageButton) layout.findViewById(R.id.refresh);
		ImageButton info = (ImageButton) layout.findViewById(R.id.info);

		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SingleLatest.this, Latest.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);

				finish();
			}
		});



		info.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				Intent intent = new Intent(SingleLatest.this,
						DialogActivity.class);
				startActivity(intent);


			}
		});

		text = (TextView) findViewById(R.id.textarticle);
		final TextView summary = (TextView) findViewById(R.id.summary);
		summary.setMovementMethod(LinkMovementMethod.getInstance());
		TextView author = (TextView) findViewById(R.id.author);
		TextView published = (TextView) findViewById(R.id.published);
		ImageView image = (ImageView) findViewById(R.id.bigimage);

		imageLoader = new ImageLoader(this.getApplicationContext());
		imageLoader.DisplayImage(FirstScreen.fList
				.get(feedValue)._itemlist.get(newsValue)
				.getbigImage(), image);
		summary.setText(FirstScreen.fList
				.get(feedValue)._itemlist.get(newsValue).getStory()
				.toString());//Html.fromHtml(
		 id=Integer.parseInt(FirstScreen.fList
				.get(feedValue)._itemlist.get(newsValue).getId());
		
		// summary.setMovementMethod(LinkMovementMethod.getInstance());
		text.setText(FirstScreen.fList.get(feedValue)._itemlist
				.get(newsValue).getTitle());
		author.setText("By: "
				+ FirstScreen.fList.get(feedValue)._itemlist
						.get(newsValue).getAuthor());
		if (FirstScreen.fList.get(feedValue)._itemlist
				.get(newsValue).getpubDate().length() > 17) {
			published.setText(FirstScreen.fList
					.get(feedValue)._itemlist.get(newsValue)
					.getpubDate().substring(0, 17));
		} else {
			published.setText(FirstScreen.fList
					.get(feedValue)._itemlist.get(newsValue)
					.getpubDate());
		}

		fontsize = (int) summary.getTextSize();
		Button button1 = (Button) findViewById(R.id.button1);

		button1.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				summary.setTextSize(fontsize + 2);
				fontsize = fontsize + 2;

			}
		});
		Button button2 = (Button) findViewById(R.id.button2);
		button2.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				summary.setTextSize(fontsize - 2);
				fontsize = fontsize - 2;
			}
		});

		ImageButton buttonemail = (ImageButton) findViewById(R.id.emailbutton);
		buttonemail.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				final Intent emailIntent = new Intent(
						android.content.Intent.ACTION_SEND);
				emailIntent.setType("plain/text");
				emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
						new String[] { "" });
				emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
						"ItWeb Africa article - " + text.getText());
				emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
						FirstScreen.fList.get(feedValue)._itemlist.get(
								newsValue).getLink().toString());

				startActivity(Intent.createChooser(emailIntent, "Send mail..."));
			}
		});

		ImageButton buttonFav = (ImageButton) findViewById(R.id.favouritesbut);
		if (checkFavorite()) {
			buttonFav.setBackgroundResource(R.drawable.star_black);
			buttonFav.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					Toast.makeText(getApplicationContext(),
							"Already in favourites", Toast.LENGTH_SHORT).show();

				}
			});

		} else {

			buttonFav.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					if (v.getTag() != "CLICKED") {

						if (addFavorite()) {
							Toast.makeText(getApplicationContext(),
									"Added to favourites", Toast.LENGTH_SHORT)
									.show();
							v.setBackgroundResource(R.drawable.star_black);
							v.setTag("CLICKED");
						} else {
							Toast.makeText(
									getApplicationContext(),
									"There has been a mistake, please try again",
									Toast.LENGTH_SHORT).show();
						}

					} else {
						Toast.makeText(getApplicationContext(),
								"Already in favourites", Toast.LENGTH_SHORT)
								.show();
					}
				}
			});

		}

	}

	public String determineDensity(){
		switch (getResources().getDisplayMetrics().densityDpi) {
		case DisplayMetrics.DENSITY_LOW:
			density2="ldpi";
			
		    break;
		case DisplayMetrics.DENSITY_MEDIUM:
			density2= "mdpi";
			
			 break;
		case DisplayMetrics.DENSITY_HIGH:
			density2= "hdpi";
			
			 break;
		case DisplayMetrics.DENSITY_XHIGH:
			density2= "xdpi";
			 break;
		}
		return density2;
	}

	public boolean addFavorite() {
		JSONArray JArray;
		try {
			SharedPreferences myPrefs = getSharedPreferences(PREFS_NAME,
					MODE_WORLD_READABLE);
			String prefName = myPrefs.getString("co.za.itweb.itwebafrica", "title");

			if (prefName.length() > 5) {
				JArray = new JSONArray(prefName);
			} else {
				JArray = new JSONArray();
			}

			JSONObject jObjectType = new JSONObject();

			try {
				jObjectType.put("feed", 1);
				jObjectType
						.put("id",
								FirstScreen.fList
										.get(FirstScreen.feedValue)._itemlist
										.get(newsValue).getId());
				jObjectType
						.put("title",
								FirstScreen.fList
										.get(FirstScreen.feedValue)._itemlist
										.get(newsValue).getTitle());

				JArray.put(jObjectType);
				StringBuilder buf = new StringBuilder();

				buf.append(JArray).append("\n");

				SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.clear();

				// SharedPreferences.Editor editor =
				// getSharedPreferences(MODE_WORLD_READABLE).edit();
				editor.putString("co.za.itweb.itwebafrica", buf.toString());
				editor.commit();
				return true;
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} catch (JSONException e) {
			e.printStackTrace();

		}
		return false;

	}

	public boolean checkFavorite() {

		try {
			SharedPreferences myPrefs = getSharedPreferences(PREFS_NAME,
					MODE_WORLD_READABLE);
			String prefName = myPrefs.getString("co.za.itweb.itwebafrica", "title");
			prefName = prefName.replaceAll("/", "");

			JSONArray dat;
			dat = new JSONArray(prefName);

			TextView currentTitle = (TextView) this
					.findViewById(R.id.textarticle);
			for (int t = 0; t < dat.length(); t++) {
				try {
					String obj = dat.getJSONObject(t).getString("title");

					if (obj.equals(currentTitle.getText().toString())) {

						return true;

					}

				} catch (JSONException e) {
					e.printStackTrace();

				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();

		}

		return false;
	}

	private class TweetTask extends AsyncTask<Void, Void, Integer> {
		private SingleLatest activity;
		ProgressDialog dialog;

		public TweetTask(SingleLatest activity) {
			this.activity = activity;
			
		}

		protected void onPreExecute() {
			dialog = new ProgressDialog(activity);
			dialog.setMessage("Tweeting...");
//			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					tt.cancel(true);
					SingleLatest.this.finish();
				}
			});
			this.dialog.show();

		}

		@Override
		protected Integer doInBackground(Void... params) {

			SharedPreferences settings = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());

			accessToken = settings.getString("twitter_access_token", null);
			accessTokenSecret = settings.getString(
					"twitter_access_token_secret", null);
			haveNetworkConnection();
			if ((haveConnectedWifi) || (haveConnectedMobile)) {

				if ((accessToken == null) || (accessTokenSecret == null)) {
					mTwitter = new TwitterFactory().getInstance();
					mRequestToken = null;
					mTwitter.setOAuthConsumer(Constants.CONSUMER_KEY,
							Constants.CONSUMER_SECRET);
					String callbackURL = getResources().getString(
							R.string.twitter_callback);
					try {
						mRequestToken = mTwitter
								.getOAuthRequestToken(callbackURL);

						return (Integer) 1;
					} catch (TwitterException e) {
						e.printStackTrace();
					}

				
				} else {
					
					return 0;
				}
			} else {
				
				return 0;
			}

			return 0;
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
				if (result == 1) {
					setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
					startIt();
				}
			}

		}
	}

	public void startIt() {
		Intent i = new Intent(SingleLatest.this, TwitterWebviewActivity.class);
		i.putExtra("URL", mRequestToken.getAuthenticationURL());
		startActivityForResult(i, TWITTER_AUTH);

	}

	private boolean haveNetworkConnection() {
		haveConnectedWifi = false;
		haveConnectedMobile = false;

		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] netInfo = cm.getAllNetworkInfo();
		for (NetworkInfo ni : netInfo) {
			if (ni.getTypeName().equalsIgnoreCase("WIFI"))
				if (ni.isConnected())
					haveConnectedWifi = true;
			if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
				if (ni.isConnected())
					haveConnectedMobile = true;
		}
		return haveConnectedWifi || haveConnectedMobile;
	}
	
	
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
		if (requestCode == TWITTER_AUTH) {

			if (resultCode == Activity.RESULT_OK) {

				oauthVerifier = (String) data.getExtras().get(
						"oauth_verifier");
				if (oauthVerifier != null) {
					rt.execute();
				} else {
					
					Toast.makeText(this,
							"There has been a mistake processing your tweet !",
							Toast.LENGTH_SHORT).show();
					if (tt.getStatus() == AsyncTask.Status.RUNNING) {
						tt.dialog.dismiss();
						tt.cancel(true);
						

					}
				}
			} else {
				
					Toast.makeText(this,
							"There has been a mistake processing your tweet !",
							Toast.LENGTH_SHORT).show();
					if (tt.getStatus() == AsyncTask.Status.RUNNING) {
						tt.dialog.dismiss();
						tt.cancel(true);
						

					}
				
			}

		} else {
			
				Toast.makeText(this,
						"There has been a mistake processing your tweet !",
						Toast.LENGTH_SHORT).show();
				if (tt.getStatus() == AsyncTask.Status.RUNNING) {
					tt.dialog.dismiss();
					tt.cancel(true);
					

				}
			
		}

	}

	
	

	private class UpdateTask extends AsyncTask<Void, Void, Integer> {

	
		ProgressDialog dialog;
		private SingleLatest activity;
		protected void onPreExecute() {
			dialog = new ProgressDialog(activity);
			dialog.setMessage("Tweeting...");

			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					ut.cancel(true);
					SingleLatest.this.finish();
				}
			});
			this.dialog.show();

		}
		public UpdateTask(SingleLatest activity) {
			this.activity = activity;
			
		}

		

		@Override
		protected Integer doInBackground(Void... params) {

			SharedPreferences settings = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			accessToken = settings.getString("twitter_access_token", null);
			accessTokenSecret = settings.getString(
					"twitter_access_token_secret", null);
			// Toast.makeText(this, accessToken, 10000).show();
			// Toast.makeText(this, accessTokenSecret, 10000).show();
			haveNetworkConnection();
			if ((haveConnectedWifi) || (haveConnectedMobile)) {
				ConfigurationBuilder builder = new ConfigurationBuilder();
				builder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
				builder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
				builder.setOAuthAccessToken(accessToken);
				builder.setOAuthAccessTokenSecret(accessTokenSecret);
				Configuration conf = builder.build();
				Twitter t = new TwitterFactory(conf).getInstance();

				try {

					t.updateStatus(text.getText().toString()
							+ " "
							+ "http://on.itweb.co.za/a/" + FirstScreen.fList
									.get(feedValue)._itemlist.get(
									newsValue).getId());
					
					return (Integer) 1;
				} catch (TwitterException e) {
					e.printStackTrace();
					return 0;
					
				}
			} else {
				
				return 0;
			}
		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}

		@Override
		protected void onPostExecute(Integer result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			updateIt(result);

		}
	}

	public void updateIt(Integer result) {
		tweetB.setBackgroundResource(R.drawable.twitter_visited);
		if (result == 1) {
			Toast.makeText(this, "Tweet successfully posted", Toast.LENGTH_SHORT).show();
			
		} else {
			Toast.makeText(
					this,
					"There has been a mistake...have you already tweeted on this topic?",
					Toast.LENGTH_SHORT).show();
		}

	}

	private class ResumeTask extends AsyncTask<String, Void, Integer> {
		private String oauth;
		ProgressDialog dialog;
        
       

		protected void onPreExecute() {
			oauth = oauthVerifier;
			dialog = new ProgressDialog(SingleLatest.this);
			dialog.setMessage("Tweeting...");

			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					rt.cancel(true);
					SingleLatest.this.finish();
				}
			});
			this.dialog.show();

		}
        
		public ResumeTask() {
			
		}

		@Override
		protected Integer doInBackground(String... params) {
			

			try {
				
				// Pair up our request with the response
				AccessToken at = mTwitter.getOAuthAccessToken(oauth);
				String theToken = at.getToken();
				// Toast.makeText(this, theToken, 10000).show();
				String theTokenSecret = at.getTokenSecret();
				// Toast.makeText(this, theTokenSecret, 10000).show();
				SharedPreferences settings = PreferenceManager
						.getDefaultSharedPreferences(getApplicationContext());
				settings = PreferenceManager
						.getDefaultSharedPreferences(getApplicationContext());
				SharedPreferences.Editor editor = settings.edit();
				editor.putString("twitter_access_token", theToken);
				editor.putString("twitter_access_token_secret", theTokenSecret);
				editor.commit();
				return (Integer) 1;

				// updateStatus();
			} catch (TwitterException e) {
				e.printStackTrace();
				return 0;
			}
		}


		@Override
		protected void onProgressUpdate(Void... values) {

		}

		@Override
		protected void onPostExecute(Integer result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			if (result == 1) {
				resumeIt();
			}

		}

		
	}

	public void resumeIt() {
		ut.execute();

	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
	    if ((keyCode == KeyEvent.KEYCODE_BACK)){
	    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
	    	if (tt.getStatus() == AsyncTask.Status.RUNNING) {
				tt.dialog.dismiss();
				tt.cancel(true);
				

			}
			
			if (rt.getStatus() == AsyncTask.Status.RUNNING) {
				rt.dialog.dismiss();
				rt.cancel(true);
				

			}
			if (ut.getStatus() == AsyncTask.Status.RUNNING) {
				ut.dialog.dismiss();
				ut.cancel(true);
			}
	    	Intent intent1 = new Intent(SingleLatest.this, Latest.class);
	    	intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent1);
			finish();
	    	 return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onBackPressed() {
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    	if (tt.getStatus() == AsyncTask.Status.RUNNING) {
			tt.dialog.dismiss();
			tt.cancel(true);
			

		}
		
		if (rt.getStatus() == AsyncTask.Status.RUNNING) {
			rt.dialog.dismiss();
			rt.cancel(true);
			

		}
		if (ut.getStatus() == AsyncTask.Status.RUNNING) {
			ut.dialog.dismiss();
			ut.cancel(true);
		}
    	Intent intent1 = new Intent(SingleLatest.this, Latest.class);
    	intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent1);
		finish();
    	 
    
		
		return;
	}
	

	@Override
	public void onPause() {
		super.onPause();
		if (tt.getStatus() == AsyncTask.Status.RUNNING) {
			tt.dialog.dismiss();
			tt.cancel(true);
			

		}
		
		if (rt.getStatus() == AsyncTask.Status.RUNNING) {
			rt.dialog.dismiss();
			rt.cancel(true);
			

		}
		if (ut.getStatus() == AsyncTask.Status.RUNNING) {
			ut.dialog.dismiss();
			ut.cancel(true);
			

		}
		

	}
	

}

